package com.youcan.controller.modelcontroller;

import java.io.IOException;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.criterion.Restrictions;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.youcan.entity.Collect;
import com.youcan.entity.User;
import com.youcan.service.modelservices.CollectService;
import com.youcan.service.modelservices.UserService;
import com.youcan.util.Constants;

/**
 * @author time E-mail:timezone85@gmail.com
 * @date:2012-8-19 上午11:07:06
 * @version :V1.0
 *
 */

@Component
@Controller
public class CollectController {
	protected final Log logger = LogFactory.getLog(CollectController.class);

	
	/**
	 * 注入需要的Service
	 * 
	 */
//	@Autowired
//	private Service<Collect,?> collectService;
	@Autowired
	@Qualifier("collectServiceImpl")
	private CollectService collectService;
	@Resource
	@Qualifier("userServiceImpl")
	private UserService userService;

	//通过注解进行转发控制 POST来的请求并把参数绑定
	@ResponseBody
	@RequestMapping(value = "/AddCollect", method = RequestMethod.POST)
	public JSONObject AddCollect(
			@RequestParam("userName") String userName,
			@RequestParam("storeId") String storeId,//商家？
			@RequestParam("goodsId") String goodsId,
			@RequestParam("type") String type,
			@RequestParam("sort") Integer sort,
			HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException, JSONException {
		
		Collect collect = new Collect();
		JSONObject jsonObject = new JSONObject();
		
		
		try {
		    List<User> userList = userService.findByCriteria(Restrictions.eq("userName", userName));
			if(!userList.isEmpty()){
				collect.setUserId(userList.get(0).getUserId());
		    }
			collect.setGoodsId(goodsId);
			collect.setStoreId(storeId);
			collect.setType(type);
			collect.setSort(sort);
			collectService.addEntity(collect);
			jsonObject.put(Constants.RES_CODE, Constants.CODE_FAILED);
			jsonObject.put(Constants.RES_MESSAGE, "收藏成功。");
		} catch (Exception e) {
			jsonObject.put(Constants.RES_CODE, Constants.CODE_FAILED);
			jsonObject.put(Constants.RES_MESSAGE, "收藏失败。");
		}
		return jsonObject;
	}
}
